package client

import (
	"awesomeTask/commom/KeyHelper"
	parseHelper "awesomeTask/commom/parse"
	"net"
	"sync"
)

var ServerConnectionsMap sync.Map

type ServerConnection struct {
	IpAddress   string
	CpuNum      float64
	Memory      float64
	FreeMemory  float64
	RunningTask int
	UsedCpu     float64
	Connetion   net.Conn
	IsInit      bool
	IsMaster    bool
	UniqueId    string
	BindIp      string
	BindPort    int
	Location    interface{}
}

type ServerConnectionHandler interface {
}

func AddConnection(conn net.Conn, info map[string]interface{}) {
	connection := ServerConnection{}
	connection.IsInit = true
	connection.UsedCpu = info["cpuUsed"].(float64)
	connection.RunningTask = parseHelper.Float64ParseInt(info["currentRun"].(float64))
	connection.Memory = info["totalMemory"].(float64)
	connection.IpAddress = conn.RemoteAddr().String()
	connection.FreeMemory = info["freeMemory"].(float64)
	connection.UniqueId = info["uniqueId"].(string)
	connection.BindIp = info["bindIp"].(string)
	connection.Location = info["location"]
	connection.BindPort = int(info["bindPort"].(float64))
	connection.Connetion = conn
	ServerConnectionsMap.Store(KeyHelper.TcpUniqueIdByConnection(conn), connection)
}
func RemoveConnection(conn net.Conn) {
	key := KeyHelper.TcpUniqueIdByConnection(conn)
	if _, ok := ServerConnectionsMap.Load(key); ok {
		ServerConnectionsMap.Delete(key)
	}
}
func ServerConnectionRange(rangeFun func(key string, connection ServerConnection)) {
	ServerConnectionsMap.Range(func(key, value interface{}) bool {
		rangeFun(key.(string), value.(ServerConnection))
		return true
	})
}
